<template>
  <div class="product-management">
    <h2>商品管理</h2>

    <!-- 连接状态指示器 -->
    <div class="connection-status" :class="{ connected: isConnected }">
      {{ isConnected ? '后端连接正常' : '后端连接异常' }}
      <button @click="testConnection" class="test-btn">测试连接</button>
    </div>

    <div class="product-form">
      <h3>添加新商品</h3>
      <form @submit.prevent="addProduct">
        <div class="form-group">
          <label>商品名称:</label>
          <input type="text" v-model="newProduct.name" required placeholder="输入商品名称">
        </div>
        <div class="form-group">
          <label>商品描述:</label>
          <textarea v-model="newProduct.description" required placeholder="输入商品描述"></textarea>
        </div>
        <div class="form-group">
          <label>价格:</label>
          <input type="number" v-model="newProduct.price" min="0" step="0.01" required placeholder="0.00">
        </div>
        <div class="form-group">
          <label>库存:</label>
          <input type="number" v-model="newProduct.stock" min="0" required placeholder="0">
        </div>
        <button type="submit" :disabled="addingProduct" class="submit-btn">
          {{ addingProduct ? '添加中...' : '添加商品' }}
        </button>
      </form>
    </div>

    <div class="product-list">
      <div class="list-header">
        <h3>商品列表</h3>
        <div class="list-actions">
          <button @click="fetchProducts" :disabled="loading" class="refresh-btn">
            <span v-if="loading">加载中...</span>
            <span v-else>刷新商品列表</span>
          </button>
          <span class="product-count">共 {{ products.length }} 个商品</span>
        </div>
      </div>

      <div v-if="loading" class="loading-state">
        <div class="spinner"></div>
        <p>正在加载商品数据...</p>
      </div>

      <div v-else-if="error" class="error-state">
        <div class="error-icon">⚠️</div>
        <h4>获取商品列表失败</h4>
        <p>{{ error }}</p>
        <button @click="fetchProducts" class="retry-btn">重试</button>
        <button @click="testConnection" class="test-btn">测试连接</button>
      </div>

      <div v-else-if="products.length === 0" class="empty-state">
        <div class="empty-icon">📦</div>
        <h4>暂无商品数据</h4>
        <p>点击"添加商品"按钮开始添加商品</p>
      </div>

      <div v-else class="products-grid">
        <div v-for="product in products" :key="product.id" class="product-card">
          <div class="product-info">
            <h4 class="product-name">{{ product.name }}</h4>
            <p class="product-description">{{ product.description }}</p>
            <div class="product-details">
              <span class="price">¥{{ product.price.toFixed(2) }}</span>
              <span class="stock">库存: {{ product.stock }}</span>
            </div>
            <p class="created-at">创建时间: {{ formatDate(product.createdAt) }}</p>
          </div>
          <div class="product-actions">
            <button @click="editProduct(product)" class="edit-btn">编辑</button>
            <button @click="confirmDelete(product)" class="delete-btn">删除</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 删除确认对话框 -->
    <div v-if="showDeleteConfirm" class="modal-overlay">
      <div class="modal">
        <h3>确认删除</h3>
        <p>确定要删除商品 "{{ productToDelete?.name }}" 吗？此操作不可恢复。</p>
        <div class="modal-actions">
          <button @click="cancelDelete" class="cancel-btn">取消</button>
          <button @click="deleteProduct" :disabled="deletingProduct" class="confirm-delete-btn">
            {{ deletingProduct ? '删除中...' : '确认删除' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

// 配置axios默认值
const API_BASE_URL = 'http://localhost:8081';
axios.defaults.timeout = 10000; // 10秒超时

export default {
  name: 'ProductView',
  data() {
    return {
      products: [],
      newProduct: {
        name: '',
        description: '',
        price: 0,
        stock: 0
      },
      loading: false,
      error: null,
      addingProduct: false,
      isConnected: false,
      showDeleteConfirm: false,
      productToDelete: null,
      deletingProduct: false
    }
  },
  mounted() {
    this.fetchProducts();
    // 初始连接测试
    this.testConnection();
  },
  methods: {
    async fetchProducts() {
      this.loading = true;
      this.error = null;
      try {
        const response = await axios.get(`${API_BASE_URL}/api/products`);
        this.products = response.data;
        this.isConnected = true;
      } catch (error) {
        console.error('获取商品列表失败:', error);
        this.isConnected = false;

        if (error.code === 'ECONNABORTED') {
          this.error = '请求超时，请检查后端服务是否正常运行';
        } else if (error.code === 'ERR_NETWORK') {
          this.error = '网络连接失败，无法连接到后端服务';
        } else if (error.response) {
          // 服务器响应了错误状态码
          this.error = `服务器错误: ${error.response.status} - ${error.response.statusText}`;
        } else if (error.request) {
          // 请求已发出但没有收到响应
          this.error = '无法连接到后端服务，请确保后端正在运行';
        } else {
          // 其他错误
          this.error = `请求错误: ${error.message}`;
        }
      } finally {
        this.loading = false;
      }
    },

    async addProduct() {
      // 验证输入
      if (!this.newProduct.name.trim()) {
        this.error = '商品名称不能为空';
        return;
      }
      if (this.newProduct.price <= 0) {
        this.error = '价格必须大于0';
        return;
      }
      if (this.newProduct.stock < 0) {
        this.error = '库存不能为负数';
        return;
      }

      this.addingProduct = true;
      this.error = null;

      try {
        const response = await axios.post(`${API_BASE_URL}/api/products`, this.newProduct);
        this.products.push(response.data);
        this.newProduct = { name: '', description: '', price: 0, stock: 0 };
        this.isConnected = true;

        // 使用 alert 显示成功消息（替代 this.$notify）
        alert('商品添加成功!');
      } catch (error) {
        console.error('添加商品失败:', error);
        this.isConnected = false;

        if (error.response) {
          this.error = `添加商品失败: ${error.response.status} - ${error.response.data}`;
        } else {
          this.error = '添加商品失败，请检查后端服务是否正常运行';
        }
      } finally {
        this.addingProduct = false;
      }
    },

    editProduct(product) {
      // 这里可以跳转到编辑页面或打开编辑模态框
      alert(`编辑商品: ${product.name}`);
    },

    confirmDelete(product) {
      this.productToDelete = product;
      this.showDeleteConfirm = true;
    },

    cancelDelete() {
      this.showDeleteConfirm = false;
      this.productToDelete = null;
    },

    async deleteProduct() {
      if (!this.productToDelete) return;

      this.deletingProduct = true;

      try {
        await axios.delete(`${API_BASE_URL}/api/products/${this.productToDelete.id}`);
        this.products = this.products.filter(p => p.id !== this.productToDelete.id);
        this.isConnected = true;

        // 使用 alert 显示成功消息（替代 this.$notify）
        alert('商品删除成功!');
      } catch (error) {
        console.error('删除商品失败:', error);
        this.isConnected = false;
        this.error = '删除商品失败，请检查后端服务是否正常运行';
      } finally {
        this.deletingProduct = false;
        this.showDeleteConfirm = false;
        this.productToDelete = null;
      }
    },

    async testConnection() {
      try {
        // 尝试访问一个简单的端点
        await axios.get(`${API_BASE_URL}/api/products/test-public`, { timeout: 5000 });
        this.isConnected = true;
        this.error = null;

        // 使用 alert 显示成功消息（替代 this.$notify）
        alert('后端服务连接正常!');
      } catch (error) {
        console.error('连接测试失败:', error);
        this.isConnected = false;
        this.error = '无法连接到后端服务';

        // 使用 alert 显示错误消息（替代 this.$notify）
        alert('无法连接到后端服务');
      }
    },

    formatDate(dateTime) {
      if (!dateTime) return '未知';
      const date = new Date(dateTime);
      return date.toLocaleString();
    }
  }
}
</script>

<style scoped>
.product-management {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.connection-status {
  padding: 10px 15px;
  border-radius: 5px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #ffebee;
  color: #c62828;
}

.connection-status.connected {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.test-btn {
  padding: 5px 10px;
  background-color: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 3px;
  cursor: pointer;
}

.test-btn:hover {
  background-color: #e0e0e0;
}

.product-form, .product-list {
  margin: 20px 0;
  padding: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.form-group {
  margin: 15px 0;
  display: flex;
  flex-direction: column;
}

label {
  font-weight: bold;
  margin-bottom: 5px;
  color: #333;
}

input, textarea {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

textarea {
  height: 80px;
  resize: vertical;
}

.submit-btn, .refresh-btn {
  padding: 10px 15px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: bold;
}

.submit-btn:hover, .refresh-btn:hover {
  background-color: #369c70;
}

.submit-btn:disabled, .refresh-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.list-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.product-count {
  color: #666;
  font-size: 14px;
}

.loading-state, .error-state, .empty-state {
  text-align: center;
  padding: 40px 20px;
}

.spinner {
  border: 4px solid #f3f3f3;
  border-top: 4px solid #42b983;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-icon, .empty-icon {
  font-size: 40px;
  margin-bottom: 15px;
}

.retry-btn {
  padding: 8px 15px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin: 10px 5px;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.product-card {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 15px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
  transition: transform 0.2s, box-shadow 0.2s;
}

.product-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.product-name {
  margin: 0 0 10px;
  color: #333;
  font-size: 18px;
}

.product-description {
  color: #666;
  margin: 0 0 15px;
  line-height: 1.4;
}

.product-details {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.price {
  font-weight: bold;
  color: #e53935;
}

.stock {
  color: #666;
}

.created-at {
  font-size: 12px;
  color: #999;
  margin: 5px 0;
}

.product-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 15px;
}

.edit-btn, .delete-btn {
  padding: 5px 10px;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  font-size: 12px;
}

.edit-btn {
  background-color: #2196f3;
  color: white;
}

.edit-btn:hover {
  background-color: #1976d2;
}

.delete-btn {
  background-color: #f44336;
  color: white;
}

.delete-btn:hover {
  background-color: #d32f2f;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  max-width: 400px;
  width: 100%;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.modal h3 {
  margin-top: 0;
  color: #333;
}

.modal p {
  margin: 15px 0;
  color: #666;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.cancel-btn, .confirm-delete-btn {
  padding: 8px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #333;
}

.cancel-btn:hover {
  background-color: #e0e0e0;
}

.confirm-delete-btn {
  background-color: #f44336;
  color: white;
}

.confirm-delete-btn:hover {
  background-color: #d32f2f;
}

.confirm-delete-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .product-management {
    padding: 10px;
  }

  .list-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .products-grid {
    grid-template-columns: 1fr;
  }

  .modal {
    margin: 20px;
    width: auto;
  }
}
</style>
